package com.ys.controller.api.outer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.config.MenuId;
import com.ys.entity.business.TpProductActive;
import com.ys.entity.business.TpProductActiveComponent;
import com.ys.entity.finance.TcwExpenseAllocationByManage;
import com.ys.entity.finance.TcwExpenseAllocationByManageItem;
import com.ys.entity.flow.YspModel;
import com.ys.entity.purchase.*;
import com.ys.entity.storage.TccAllocate;
import com.ys.entity.storage.TccStockControl;
import com.ys.entity.storage.TccStockControlRunning;
import com.ys.entity.storage.TccStockSource;
import com.ys.entity.sys.TsUserChange;
import com.ys.entity.sys.YsMenu;
import com.ys.mapper.finance.TcwExpenseAllocationByManageItemMapper;
import com.ys.mapper.finance.TcwExpenseAllocationByManageMapper;
import com.ys.mapper.purchase.*;
import com.ys.mapper.storage.TccStockControlRunningMapper;
import com.ys.mapper.storage.TccStockSourceMapper;
import com.ys.service.business.TcwAccountDetailedForCompanyService;
import com.ys.service.flow.YspTaskService;
import com.ys.service.purchase.TcgPurchaseInStorageService;
import com.ys.service.purchase.TcgPurchasePreStorageService;
import com.ys.service.storage.TccAssembleService;
import com.ys.service.storage.TccDistributeService;
import com.ys.service.storage.impl.TccDistributeImpl;
import com.ys.service.sys.CommonApiService;
import com.ys.util.ApiHttpUtils;
import com.ys.util.RandomUtil;
import com.ys.util.excel.ReadExcel;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.Flow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

@Controller
@RequestMapping("/api/outer/demoFXZ")
public class ApiOuterDemoFXZController {
	private static final Logger logger = LoggerFactory.getLogger(ApiOuterDemoFXZController.class);
	private final Long MENUID = MenuId.TCG_PurchasePreStorage;
	private final Long MENUID1 = MenuId.TCG_PurchaseInStorage;
	@Autowired
	private CommonApiService<TcgPurchasePreStorage> commonApiService;
	@Autowired
	private TcgPurchasePreStorageMapper tcgPurchasePreStorageMapper;

	@Autowired
	private YspTaskService yspTaskService;

	@Autowired
	private TcgPurchasePreStorageSonMapper tcgPurchasePreStorageSonMapper;

	@Autowired
	private TcgPurchaseContractItemMapper tcgPurchaseContractItemMapper;

	@Autowired
	private TcgPurchasePreStorageService tcgPurchasePreStorageService;

	@Autowired
	private TcgPurchaseInStorageMapper tcgPurchaseInStorageMapper;

	@Autowired
	private TcgPurchaseInStorageService tcgPurchaseInStorageService;

	@Autowired
	private TccAssembleService tccAssembleService;

	@Autowired
	private TccStockControlRunningMapper tccStockControlRunningMapper;

	@Autowired
	private TccStockSourceMapper tccStockSourceMapper;

	@Autowired
	private TcgPurchaseAppointOrderMapper tcgPurchaseAppointOrderMapper;

	@Autowired
	private CommonApiService<TcgPurchaseAppointOrder> commonApiServiceAppointOrder;

	@Autowired
	private TcgPurchaseAppointOrderItemMapper tcgPurchaseAppointOrderItemMapper;

	@Autowired
	private TcgPurchaseAppointOrderProductComponentMapper tcgPurchaseAppointOrderProductComponentMapper;

	@Autowired
	private TcwExpenseAllocationByManageMapper tcwExpenseAllocationByManageMapper;

	@Autowired
	private TcwExpenseAllocationByManageItemMapper tcwExpenseAllocationByManageItemMapper;

	@Autowired
	private TcwAccountDetailedForCompanyService tcwAccountDetailedForCompanyService;
	@Autowired
	private TccDistributeService tccDistributeService;

	@Autowired
	private TccDistributeImpl tccDistributeImpl;


    @RequestMapping("/test")
	@ResponseBody
	public void test() {
    	try {
			//采购预入库逻辑
			logger.info("*************采购预入库开始*************");
			//读取本地文件
			FileInputStream fileInputStream = new FileInputStream(new File("C:/Users/Administrator/Desktop/采购预入库.xlsx"));
			List<List<String>> res = ReadExcel.getRowsByInputStream(fileInputStream,0);
			System.out.println("res:\n"+res);
			for (List<String> bids : res){
				String bid = commonApiService.getCommonNextBid(MENUID);
				//TODO 根据线上的制单人
				Long createChangeId = 1030L;
				TcgPurchasePreStorage tcgPurchasePreStorage =
						TcgPurchasePreStorage.tcgPurchasePreStorage(
								bid,createChangeId,1,"批量操作数据",bids.get(0),"2024-09-25","福沃洋","123",1);
				tcgPurchasePreStorageMapper.insert(tcgPurchasePreStorage);

				//新增采购预入库子件数据
				List<TcgPurchaseContractItem> tcgPurchaseContractItemList = new TcgPurchaseContractItem()
						.setPbid(bids.get(0))
						.queryList();
				for (TcgPurchaseContractItem tcgPurchaseContractItem : tcgPurchaseContractItemList){
					Integer num = tcgPurchaseContractItem.getSubPurchaseNum() - tcgPurchaseContractItem.getSubPreWarehousingNum();
					TcgPurchasePreStorageSon tcgPurchasePreStorageSon =
							TcgPurchasePreStorageSon.tcgPurchasePreStorageSon(bid,tcgPurchaseContractItem.getId(), num,num,1);
					tcgPurchasePreStorageSonMapper.insert(tcgPurchasePreStorageSon);

					//增加预入库数量
					tcgPurchaseContractItem.setSubPreWarehousingNum(num);
					tcgPurchaseContractItemMapper.update(tcgPurchaseContractItem);
				}

				YsMenu ysMenu = new YsMenu().setId(MENUID).queryFirst();
				if (ysMenu.getFlowModelId().longValue() != 0L) {
					YspModel yspModel = new YspModel().setId(ysMenu.getFlowModelId()).queryFirst();
					String codeModel = yspModel.getCode();
					String createUserId = ShiroUtils.getUserId();
					yspTaskService.init(codeModel, tcgPurchasePreStorage.getBid(), createUserId);
				}

				//流转
				tcgPurchasePreStorageService.flowPass(tcgPurchasePreStorage.getBid(), ShiroUtils.getUserId());
				tcgPurchasePreStorageService.flowPass(tcgPurchasePreStorage.getBid(), ShiroUtils.getUserId());
				logger.info("*************新增结束*************"+tcgPurchasePreStorage.getBid() + "采购单号" + tcgPurchasePreStorage.getPurchaseContractBid());
			}
			logger.info("*************采购预入库结束*************");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	@RequestMapping("/test1")
	@ResponseBody
	public void test1() {
		try {
			//采购预入库逻辑
			logger.info("*************采购入库开始*************");
			//读取本地文件
			FileInputStream fileInputStream = new FileInputStream(new File("C:/Users/Administrator/Desktop/采购入库.xlsx"));
			List<List<String>> res = ReadExcel.getRowsByInputStream(fileInputStream, 0);
			System.out.println("res:\n" + res);
			Map<String, Object> params = new HashMap<>();
			for (int i = 0; i < res.size(); i++) {
				String bid = res.get(i).get(0);
				//选择货位
				TcgPurchaseInStorage tcgPurchaseInStorage = new TcgPurchaseInStorage().setBid(bid).queryFirst();
				logger.info("*************开始*************" + tcgPurchaseInStorage.getBid());
				//				选择货位 TODO 根据线上的仓库编号来 先执行 在完成下面的审核
				tcgPurchaseInStorage.setChw("HW00001");
				tcgPurchaseInStorageMapper.update(tcgPurchaseInStorage);
				logger.info("*************结束*************");
			}
			logger.info("*************采购入库结束*************");
//			int i = 1/0;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@RequestMapping("/test44")
	@ResponseBody
	public void test44() {
		try {
			//采购预入库逻辑
			logger.info("*************采购入库开始*************");
			//读取本地文件
			FileInputStream fileInputStream = new FileInputStream(new File("C:/Users/Administrator/Desktop/采购入库.xlsx"));
			List<List<String>> res = ReadExcel.getRowsByInputStream(fileInputStream, 0);
			System.out.println("res:\n" + res);
			Map<String, Object> params = new HashMap<>();
			for (int i = 0; i < res.size(); i++) {
				String bid = res.get(i).get(0);
				//选择货位
				TcgPurchaseInStorage tcgPurchaseInStorage = new TcgPurchaseInStorage().setBid(bid).queryFirst();
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.append("[");
				stringBuilder.append(tcgPurchaseInStorage.getId());
				stringBuilder.append("]");
				params.put("listId",stringBuilder);
				logger.info("*************开始*************" + tcgPurchaseInStorage.getBid());
				tcgPurchaseInStorageService.updateSh(params,MENUID1);
				logger.info("*************结束*************");
			}
			logger.info("*************采购入库结束*************");
//			int i = 1/0;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	@RequestMapping("/test2")
	@ResponseBody
	public void test2() {
		try {
			//商品组装逻辑
			logger.info("*************商品组装开始*************");
			//读取本地文件
			FileInputStream fileInputStream = new FileInputStream(new File("C:/Users/Administrator/Desktop/商品组装.xlsx"));
			List<List<String>> res = ReadExcel.getRowsByInputStream(fileInputStream, 0);
			for (int i = 0; i < res.size(); i++) {
				String bid = res.get(i).get(0);
				logger.info("*************开始*************" + bid);
				tccAssembleService.pass(bid);
				logger.info("*************结束*************" + bid);
			}
			logger.info("*************商品组装结束*************");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	@RequestMapping("/test3")
	@ResponseBody
	public void test3() {
		try {
			//商品组装逻辑
			logger.info("*************库存开始*************");
			//读取本地文件
			FileInputStream fileInputStream = new FileInputStream(new File("C:/Users/Administrator/Desktop/库存.xlsx"));
			List<List<String>> res = ReadExcel.getRowsByInputStream(fileInputStream, 0);
			for (int i = 0; i < res.size(); i++) {
				Long stockControlId = Math.round(Double.parseDouble(res.get(i).get(0)));
				TccStockControlRunning tccStockControlRunning = new TccStockControlRunning().setStockControlId(stockControlId).queryFirst();
				TccStockSource tccStockSource = new TccStockSource().setStockControlRunningId(tccStockControlRunning.getId()).queryFirst();

				List<TccStockControl> tccStockControlList = new TccStockControl().setProductCode(tccStockControlRunning.getProductCode())
						.where("A.productNum != 0 AND A.productNumAll != 0 AND  A.id !=" + stockControlId)
						.queryList();
				for (TccStockControl tccStockControl : tccStockControlList){
					logger.info("*************新增库存流水开始*************");
					//新增库存流水
					TccStockControlRunning tccStockControlRunning1 = TccStockControlRunning.tccStockControlRunning(tccStockControl.getId(), RandomUtil.getGUID()
							,tccStockControl.getGuid(),tccStockControlRunning.getBidRelative(),tccStockControlRunning.getVGsBm(),
							tccStockControlRunning.getProductCode(),tccStockControl.getProductNum(),tccStockControl.getProductNumAll()
							,tccStockControl.getChw(),"批量导入数据用于关联组装单(虚拟数据)",1);
				tccStockControlRunningMapper.insert(tccStockControlRunning1);
					//新增库存来源
					//新增流水对应的数据来源等字段信息
					TccStockSource tccStockSource1 = TccStockSource.tccStockSource(
							tccStockSource.getSourceType(),tccStockSource.getSourceBid(),
							tccStockSource.getSourceId(),tccStockControlRunning1.getId(),tccStockSource.getAssembleBid(),1,1);
					tccStockSourceMapper.insert(tccStockSource1);
					logger.info("*************新增库存流水结束*************");
				}

			}
			logger.info("*************库存结束*************");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@RequestMapping("/test4")
	@ResponseBody
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public void test4() {
		try {
			//商品组装逻辑
			logger.info("*************预约单开始*************");
			//读取本地文件
			FileInputStream fileInputStream = new FileInputStream(new File("C:/Users/Administrator/Desktop/预约采购导入1.xlsx"));
			List<List<String>> res = ReadExcel.getRowsByInputStream(fileInputStream, 0);
			Map<String, Object> params = new HashMap<String, Object>();
			List<Map<String,Object>> dataList = new ArrayList<>();
			Map<String,Object> data;
			for (int i = 1; i < res.size(); i++) {
				dataList = new ArrayList<>();
				data = new HashMap<>();
				//购买方
				data.put("companyVid",res.get(i).get(1));
				//运营公司
				data.put("vgsbm",res.get(i).get(2));
				//子件商品编码
				data.put("subCode",res.get(i).get(3));
				//母件采购数量
				data.put("reserveNumber",Math.round(Double.parseDouble(res.get(i).get(4))));
				//先分组单号
				if (params.get(res.get(i).get(0)) == null){
					dataList.add(data);
				}else {
					params.get(res.get(i).get(0));
					dataList = (List<Map<String, Object>>) params.get(res.get(i).get(0));
					dataList.add(data);
				}
				params.put(res.get(i).get(0),dataList);
			}

			//Lambda表达式
			params.forEach((k,v) ->{
				try {
					System.out.println(k + "=====" + v);
					JSONArray jsonArray = JSONArray.parseArray(JSONObject.toJSONString(v));

					JSONObject jsonObject = JSONObject.parseObject(String.valueOf(jsonArray.get(0)));
					String bid = commonApiServiceAppointOrder.getCommonNextBid(MenuId.TCG_PurchaseAppointOrder);

					//根据单号新增采购预约单
					String loginUserId = ShiroUtils.getUserId();
					TsUserChange tsUserChange = new TsUserChange().setUserId(loginUserId).setStatus(1).queryFirst();

					TcgPurchaseAppointOrder tcgPurchaseAppointOrder = TcgPurchaseAppointOrder.tcgPurchaseAppointOrder(
							bid, tsUserChange.getId(), null, 1, jsonObject.get("vgsbm").toString(), null, jsonObject.get("companyVid").toString(), "批量导入",
							0, 1);
					BigDecimal bpriceTol = BigDecimal.ZERO;
					Map<String, Object> isNullPcode = new HashMap<String, Object>();
					for (int i = 0; i < jsonArray.size(); i++) {
						JSONObject jsonObjectNew = JSONObject.parseObject(String.valueOf(jsonArray.get(i)));

						//查询母件信息
						Map<String,Object> entity = new TpProductActiveComponent().
								setCode(jsonObjectNew.get("subCode").toString())
								.addLeftJoin("TP_ProductActive B ON B.code = A.pcode")
								.addField("B.code pcode,B.name pname,B.codeMerge pcodeMerge")
								.queryFirstMap();

						//是否有新增过这个母件
						if (isNullPcode.get(entity.get("pcode").toString()) == null){
							isNullPcode.put(entity.get("pcode").toString(),1);
							List<TpProductActiveComponent> tpProductActiveComponentList = new TpProductActiveComponent().setPcode(entity.get("pcode").toString()).queryList();
							//新增预约采购单母件表
							TcgPurchaseAppointOrderItem tcgPurchaseAppointOrderItem = TcgPurchaseAppointOrderItem.tcgPurchaseAppointOrderItem(
									bid,entity.get("pcode").toString(),entity.get("pname").toString(),entity.get("pcodeMerge").toString(),
									Integer.valueOf(jsonObjectNew.get("reserveNumber").toString()),1
							);
							tcgPurchaseAppointOrderItemMapper.insert(tcgPurchaseAppointOrderItem);

							for (TpProductActiveComponent tpProductActiveComponent1 : tpProductActiveComponentList){
								long num = Math.round(Double.parseDouble(tpProductActiveComponent1.getNum().toString()));
								//新增预约采购单子表数据
								TcgPurchaseAppointOrderProductComponent tcgPurchaseAppointOrderProductComponent = TcgPurchaseAppointOrderProductComponent.tcgPurchaseAppointOrderProductComponent(
										tcgPurchaseAppointOrderItem.getId(),tpProductActiveComponent1.getCode(),tpProductActiveComponent1.getName(),tpProductActiveComponent1.getSubCodeMerge(),
										Integer.valueOf(num+""),tpProductActiveComponent1.getBprice(),Integer.valueOf(jsonObjectNew.get("reserveNumber").toString()),
										tpProductActiveComponent1.getBprice(),0,0,0,0,1
								);
								tcgPurchaseAppointOrderProductComponentMapper.insert(tcgPurchaseAppointOrderProductComponent);

								bpriceTol = bpriceTol.add(tpProductActiveComponent1.getBprice());
							}
						}
					}
					tcgPurchaseAppointOrder.setPreAccount(bpriceTol);
					tcgPurchaseAppointOrderMapper.insert(tcgPurchaseAppointOrder);

					//新增流程逻辑
					YsMenu ysMenu = new YsMenu().setId(MenuId.TCG_PurchaseAppointOrder).queryFirst();
					if (ysMenu.getFlowModelId().longValue() != 0L) {
						YspModel yspModel = new YspModel().setId(ysMenu.getFlowModelId()).queryFirst();
						String codeModel = yspModel.getCode();
						String createUserId = ShiroUtils.getUserId();
						yspTaskService.init(codeModel, tcgPurchaseAppointOrder.getBid(), createUserId);
					}

					Flow f = yspTaskService.flowPass(bid, loginUserId);
				} catch (Exception e) {
						e.printStackTrace();
				}

			});
//			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();


			logger.info("*************预约单结束*************");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		}

	@RequestMapping("/test333")
	@ResponseBody
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public void test333() {
		LocalDate specificDay = LocalDate.of(2024, 10, 25);
		LocalDateTime localDateTime = specificDay.atStartOfDay();
		Date specifiedDate = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());

		TcwExpenseAllocationByManage entity = TcwExpenseAllocationByManage.tcwExpenseAllocationByManage(
				"FYHBGL-241025-1004",1,1260L,"C111","","","","2000",specifiedDate,"平账",1
		);
		TcwExpenseAllocationByManageItem sonItem = TcwExpenseAllocationByManageItem.tcwExpenseAllocationByManageItem(
				"FYHBGL-241025-1004","GS0376","上海旭发","GS0300","特莱德","运营服务→划拨费用",
				new BigDecimal(2000),"平账",1
		);

		tcwExpenseAllocationByManageMapper.insert(entity);
		tcwExpenseAllocationByManageItemMapper.insert(sonItem);

		YsMenu ysMenu = new YsMenu().setId(MenuId.TCW_ExpenseAllocation_ByManage).queryFirst();
		if (ysMenu.getFlowModelId().longValue() != 0L) {
			YspModel yspModel = new YspModel().setId(ysMenu.getFlowModelId()).queryFirst();
			String codeModel = yspModel.getCode();
			String createUserId = ShiroUtils.getUserId();
			try {
				yspTaskService.init(codeModel, entity.getBid(), createUserId);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		/*
		 * 新增流水
		 */
		try {
			tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJc(
					sonItem.getVgsbmout(),sonItem.getVgsjcout(),sonItem.getVgsbmin(),sonItem.getVgsjcin(),sonItem.getBaseInfoType(),sonItem.getAmount().negate(),sonItem.getCreateTime(),sonItem.getUpdateTime(),
					"费用划拨管理单:"+entity.getBid()+",备注:"+(sonItem.getRemark()!=null?sonItem.getRemark():""),entity.getBid(),entity.getWriteTime());
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJc(
					sonItem.getVgsbmin(),sonItem.getVgsjcin(),sonItem.getVgsbmout(),sonItem.getVgsjcout(),sonItem.getBaseInfoType(),sonItem.getAmount(),sonItem.getCreateTime(),sonItem.getUpdateTime(),
					"费用划拨管理单:"+entity.getBid()+",备注:"+(sonItem.getRemark()!=null?sonItem.getRemark():""),entity.getBid(),entity.getWriteTime());
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@RequestMapping("/test3333")
	@ResponseBody
	public void test3333(){
		//预约调拨在前的先分配 还存在未分配
		List<TccAllocate> tccAllocateList = new TccAllocate().setEffectStock(1)
				.where("(SELECT count(1) From TCC_AllocateDetail B WHERE A.bid = B.bidAllocate AND B.StateDistribute = 0 AND B.DistributeNum >= 0 AND B.MayDistributeNum > 0) >0")
				.setOrderby("A.CreateTime DESC")
				.queryList();
		for(TccAllocate tccAllocate : tccAllocateList){
			tccDistributeService.automaticAllocation(tccAllocate);
		}
	}

	@RequestMapping("/test3333123")
	@ResponseBody
	public void test3333123(){
		try {
			tccDistributeImpl.afterFlowFinish1(7824L);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 查询仓库信息
	 */
	@RequestMapping("/test123")
	@ResponseBody
	public void test123(){
		try {
			String serverURL = "http://8.134.39.115:8000";
			String uriWithQueryString = "/api/v1/common/getbasedata";

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("FACTNO","003");
			jsonObject.put("SUPNO","KY05156");
			jsonObject.put("SUPPASS","KY05156");
			jsonObject.put("APPKEY","1959825b3cf2665dc2e51bb9fadd9981");
			jsonObject.put("TYPENO","PPTYPE");//仓库类型


			Map<String, String> paramsHerder = new HashMap<String, String>();
			paramsHerder.put("Content-Type", "application/json;charset=UTF-8");

			String content = JSONObject.toJSONString(jsonObject);

			String result = ApiHttpUtils.sendPostBody(serverURL + uriWithQueryString,
					content, paramsHerder);

			result = result;
			JSONObject resultJO = JSON.parseObject(result);
			JSONObject data = JSON.parseObject(resultJO.get("data").toString());
			JSONArray details = JSON.parseArray(data.get("details").toString());
			for (int i = 0; i < details.size(); i++) {
				//TODO 是否将对方的仓库信息填写
				JSONObject conditionJO = details.getJSONObject(i);
				//仓库编码

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

